package org.mindrive.system.util;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 身份证验证工具
 *
 * @author houwei
 */
public class IdentityCardVerifyUtil {

    // 省(直辖市)码表
    private static String provinceCode[] = {"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34",
            "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64"
            , "65", "71", "81", "82", "91"};

    // 身份证前17位每位加权因子
    private static int[] power = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    // 身份证第18位校检码
    private static String[] refNumber = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

    /**
     * 二代身份证号码有效性校验
     *
     * @param idNo
     * @return
     */
    public static boolean isValidIdNo(String idNo) {
        return isIdNoPattern(idNo) && isValidProvinceId(idNo.substring(0, 2)) && isValidDate(
                idNo.substring(6, 14)) && checkIdNoLastNum(idNo);
    }

    /**
     * 二代身份证正则表达式
     *
     * @param idNo
     * @return
     */
    private static boolean isIdNoPattern(String idNo) {
        return Pattern.matches("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$",
                idNo);
    }

    /**
     * 检查身份证的省份信息是否正确
     *
     * @param provinceId
     * @return
     */
    public static boolean isValidProvinceId(String provinceId) {
        for (String id : provinceCode) {
            if (id.equals(provinceId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断日期是否有效
     *
     * @param inDate
     * @return
     */
    public static boolean isValidDate(String inDate) {
        if (inDate == null) {
            return false;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        if (inDate.trim().length() != dateFormat.toPattern().length()) {
            return false;
        }
        dateFormat.setLenient(false);// 执行严格的日期匹配
        try {
            dateFormat.parse(inDate.trim());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 计算身份证的第十八位校验码
     *
     * @param cardIdArray
     * @return
     */
    public static String sumPower(int[] cardIdArray) {
        int result = 0;
        for (int i = 0; i < power.length; i++) {
            result += power[i] * cardIdArray[i];
        }
        return refNumber[(result % 11)];
    }

    /**
     * 校验身份证第18位是否正确(只适合18位身份证)
     *
     * @param idNo
     * @return
     */
    public static boolean checkIdNoLastNum(String idNo) {
        if (idNo.length() != 18) {
            return false;
        }
        char[] tmp = idNo.toCharArray();
        int[] cardidArray = new int[tmp.length - 1];
        int i = 0;
        for (i = 0; i < tmp.length - 1; i++) {
            cardidArray[i] = Integer.parseInt(tmp[i] + "");
        }
        String checkCode = sumPower(cardidArray);
        String lastNum = tmp[tmp.length - 1] + "";
        if (lastNum.equals("x")) {
            lastNum = lastNum.toUpperCase();
        }
        if (!checkCode.equals(lastNum)) {
            return false;
        }
        return true;
    }

    /**
     * 前十七位加权因子
     */
    private static int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    /**
     * 这是除以11后，可能产生的11位余数对应的验证码
     */
    private static String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

    /**
     * 15位身份证生日前缀
     */
    private static String CENTURY = "19";

    /**
     * 身份证性别中文描述
     */
    private static String[] CHINESS_SEX = {"女", "男"};

    /**
     * 18\15位
     */
    private static int IDCARD_LENTH_18 = 18;
    private static int IDCARD_LENTH_15 = 15;

    /**
     * 对应省市
     */
    private static List<Province> provinces = new ArrayList<>(35);

    static {
        provinces.add(new Province("11", "北京"));
        provinces.add(new Province("12", "天津"));
        provinces.add(new Province("13", "河北"));
        provinces.add(new Province("14", "山西"));
        provinces.add(new Province("15", "内蒙古"));
        provinces.add(new Province("21", "辽宁"));
        provinces.add(new Province("22", "吉林"));
        provinces.add(new Province("23", "黑龙江"));
        provinces.add(new Province("31", "上海"));
        provinces.add(new Province("32", "江苏"));
        provinces.add(new Province("33", "浙江"));
        provinces.add(new Province("34", "安徽"));
        provinces.add(new Province("35", "福建"));
        provinces.add(new Province("36", "江西"));
        provinces.add(new Province("37", "山东"));
        provinces.add(new Province("41", "河南"));
        provinces.add(new Province("42", "湖北"));
        provinces.add(new Province("43", "湖南"));
        provinces.add(new Province("44", "广东"));
        provinces.add(new Province("45", "广西"));
        provinces.add(new Province("46", "海南"));
        provinces.add(new Province("50", "重庆"));
        provinces.add(new Province("51", "四川"));
        provinces.add(new Province("52", "贵州"));
        provinces.add(new Province("53", "云南"));
        provinces.add(new Province("54", "西藏"));
        provinces.add(new Province("61", "陕西"));
        provinces.add(new Province("62", "甘肃"));
        provinces.add(new Province("63", "青海"));
        provinces.add(new Province("64", "宁夏"));
        provinces.add(new Province("65", "新疆"));
        provinces.add(new Province("71", "台湾"));
        provinces.add(new Province("81", "香港"));
        provinces.add(new Province("82", "澳门"));
        provinces.add(new Province("91", "国外"));

    }

    /**
     * 从身份证中获取性别 0：女 1：男
     *
     * @param idcard 身份证号
     * @return int
     */
    public static int getSex(String idcard) {
        int len = idcard.length();
        if (len == IDCARD_LENTH_18) {
            return Integer.parseInt(idcard.substring(16).substring(0, 1)) % 2;
        } else {
            return Integer.parseInt(idcard.substring(14, 15)) % 2;
        }
    }

    /**
     * 获得出身日期
     *
     * @param idcard 身份证号
     * @return LocalDate
     */
    public static LocalDate getBirthday(String idcard) {
        int len = idcard.length();
        if (len == IDCARD_LENTH_18) {
            return LocalDate.parse(idcard.substring(6, 14), DateTimeFormatter.ofPattern("yyyyMMdd"));
        } else {
            return LocalDate.parse(CENTURY + idcard.substring(6, 12), DateTimeFormatter.ofPattern("yyyyMMdd"));
        }
    }

    /**
     * 获得年龄
     *
     * @param idcard 身份证号
     * @return long
     */
    public static long getAge(String idcard) {
        return getBirthday(idcard).until(LocalDate.now(), ChronoUnit.YEARS);
    }

    /**
     * 获取性别中文标志
     */
    public static String getChineseSex(String idcard) {
        return CHINESS_SEX[getSex(idcard)];
    }

    /**
     * 获取对应省份
     *
     * @param idcard 身份证号
     * @return String
     */
    public static String getProvince(String idcard) {
        String provinceId = idcard.substring(0, 2);
        Optional<Province> province = provinces.stream().filter(e -> e.getId().equals(provinceId)).findFirst();
        return province.map(province1 -> ((Province) province1).getName()).orElse(null);
    }



    /**
     * 身份证校验 18和15位
     *
     * @param idcard 身份证号
     * @return boolean
     */
    public static boolean checkIDCard(String idcard) {
        if (idcard == null || "".equals(idcard)) {
            return false;
        }
        String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)" +
                "\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
        boolean isTrue = idcard.matches(regularExpression);
        if (isTrue) {
            if (idcard.length() == IDCARD_LENTH_18) {
                char[] charArray = idcard.toCharArray();
                int sum = 0;
                int k = idCardWi.length;
                for (int i = 0; i < k; i++) {
                    int current = Integer.parseInt(String.valueOf(charArray[i]));
                    int count = current * idCardWi[i];
                    sum += count;
                }
                char idCardLast = charArray[17];
                int idCardMod = sum % 11;
                return idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase());
            } else {
                return true;

            }
        } else {
            return false;
        }
    }

    /**
     * 18为身份证转15位
     *
     * @param idcard 身份证号
     * @return String
     */
    public static String turnTo15(String idcard) {
        if (idcard.length() == IDCARD_LENTH_15) {
            return idcard;
        }
        return idcard.substring(0, 6) + idcard.substring(8, 17);
    }

    /**
     * 15位转18位
     *
     * @param idcard 身份证
     * @return String
     */
    public static String turnTo18(String idcard) {
        if (idcard.length() == IDCARD_LENTH_18) {
            return idcard;
        }
        // 加上两位年19
        String id17 = idcard.substring(0, 6) + CENTURY + idcard.substring(6);
        // 十七位数字本体码加权求和
        int sum = 0;
        int len = 17;
        for (int i = 0; i < len; i++) {
            sum = sum + Integer.valueOf(id17.substring(i, i + 1)) * idCardWi[i];
        }
        // 计算模
        int y = sum % 11;
        // 通过模得到对应的校验码
        return id17 + idCardY[y];
    }

    public static void main(String[] args) {
        // 数据测试
        String str0 = "21010319580124124X";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "00000x190001011231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000210001011231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000191301011231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "00000019x301011231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000190013011231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000190012131231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000190012211231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "00000019001221x231";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "00000019000101123x";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "00000019000101123X";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000000101123";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "00000000010112x";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000000132123";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "000000001322123";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = null;
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "123";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "0000001900010112301";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "0000001900010112301";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "0000001900010112301";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "350424870506202";
        System.out.println(str0 + ":" + checkIDCard(str0));
        str0 = "220223198206177024";
        System.out.println(str0 + ":" + checkIDCard(str0));

    }

}
